package com.guigu.auth.controller;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.auth.entity.*;
import com.guigu.auth.entity.vo.AuthMenuVO;
import com.guigu.auth.service.AuthRoleAuthorityService;
import com.guigu.auth.service.AuthRoleService;
import com.guigu.auth.service.AuthUserRoleService;
import com.guigu.tms.exception.TmsException;
import com.guigu.tms.result.R;
import com.guigu.tms.result.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色 前端控制器
 * </p>
 *
 * @author TaoLong
 * @since 2021-12-06
 */
@RestController
@RequestMapping("/auth/auth-role")
@Api(tags = "角色管理")
@CacheConfig(cacheNames = {"authResource", "authMenu"})
public class AuthRoleController {

    @Autowired
    private AuthRoleService roleService;

    @Autowired
    private AuthUserRoleService authUserRoleService;

    @Autowired
    private AuthRoleAuthorityService authRoleAuthorityService;

    /**
     * 查询所有角色信息
     *
     * @return
     */
    @ApiOperation("查询所有角色信息")
    @GetMapping("/queryAll")
    public R<List<AuthRole>> queryAll() {
        return new R<>(ResultCode.SUCCESS_CODE, roleService.list(null));
    }


    /**
     * 角色添加
     *
     * @param authRole
     * @return
     */
    @ApiOperation("角色添加")
    @PostMapping("/addRole")
    public R addRole(@RequestBody AuthRole authRole) {
        if (ObjectUtils.isEmpty(authRole)) {
            throw new TmsException(ResultCode.ERROR_CODE, "对象为空!");
        }
        authRole.setCreateTime(new Date());
        roleService.save(authRole);
        return new R(ResultCode.SUCCESS_CODE, "角色添加成功!", true);
    }

    /**
     * 岗位绑定角色
     *
     * @param list
     * @return
     */
    @ApiOperation("岗位绑定角色")
    @PostMapping("/stationBindingRole")
    @ApiImplicitParam(name = "list", value = "岗位和角色之间的关联")
    @CacheEvict(allEntries = true)
    public R stationBindingRole(@RequestBody List<AuthUserRole> list) {
        if (CollUtil.isEmpty(list)) {
            throw new TmsException(ResultCode.ERROR_CODE, "集合为空!");
        }
        list.stream().forEach(authUserRole -> {
            QueryWrapper<AuthUserRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id", authUserRole.getRoleId());
            authUserRoleService.remove(queryWrapper);
        });
        list.stream().forEach(e -> {
            if (null != e.getUserId()) {
                authUserRoleService.saveOrUpdate(e);
            }
        });
        return new R(ResultCode.SUCCESS_CODE, "给用户分配角色成功!", true);
    }


    /**
     * 给角色分配菜单
     *
     * @param list
     * @return
     */
    @PostMapping("/roleBindingMenu")
    @ApiImplicitParam(name = "list", value = "角色和菜单之间的关联")
    @ApiOperation(("给角色分配菜单"))
    @CacheEvict(allEntries = true)
    public R roleBindingMenu(@RequestBody List<AuthRoleAuthority> list) {
        if (CollUtil.isEmpty(list)) {
            throw new TmsException(ResultCode.ERROR_CODE, "集合数据为空!");
        }
        list.stream().forEach(authRoleAuthority -> {
            QueryWrapper<AuthRoleAuthority> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id", authRoleAuthority.getRoleId());
            authRoleAuthorityService.remove(queryWrapper);
        });
        list.stream().forEach(e -> {
            if (null != e.getAuthorityId()) {
                authRoleAuthorityService.saveOrUpdate(e);
            }
        });

        return new R(ResultCode.SUCCESS_CODE, "给角色分配菜单权限成功!", true);
    }


    /**
     * 根据角色Id查询对应的岗位
     *
     * @param roleId
     * @return
     */
    @GetMapping("/getStationBasedOnRoleId/{roleId}")
    @ApiOperation("根据角色Id查询对应的岗位")
    public R<List<Long>> getStationBasedOnRoleId(@PathVariable String roleId) {
        if (StringUtils.isBlank(roleId)) {
            throw new TmsException(ResultCode.ERROR_CODE, "角色Id为空!");
        }
        QueryWrapper<AuthUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        List<AuthUserRole> list = authUserRoleService.list(queryWrapper);
        if (CollUtil.isNotEmpty(list)) {
            List<Long> longList = list.stream().map(authUserRole -> authUserRole.getUserId()).collect(Collectors.toList());
            return new R<>(ResultCode.SUCCESS_CODE, longList);
        }
        return new R<>(ResultCode.SUCCESS_CODE, null);
    }
}

